package erp

import (
	"context"
	"encoding/json"
	"strconv"
	"strings"

	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/backend/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/erp"
	"mall/service/order/rpc/orderclient"

	// "mall/service/product/rpc/productclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type SyncOrderStatusFromErpLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 库存同步
func NewSyncOrderStatusFromErpLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SyncOrderStatusFromErpLogic {
	return &SyncOrderStatusFromErpLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 订单发货状态查询
func (l *SyncOrderStatusFromErpLogic) SyncOrderStatusFromErp(req *types.SyncOrderStatusFromErpReq) (*types.BaseMsgResp, error) {
	if req.TradeIds != nil && len(*req.TradeIds) > 0 {
		shopType := strconv.FormatUint(l.svcCtx.Config.Erp.ShopType, 10)
		queryMap := map[string]string{
			"shop_nick": l.svcCtx.Config.Erp.ShopNick,     // 万里牛B2C店铺昵称，必须和订单推送中的店铺昵称相同  string
			"shop_type": shopType,                         // 店铺类型，B2C 平台店铺类型：100
			"trade_ids": strings.TrimSpace(*req.TradeIds), // 订单号(trades/open推送的trade_id)，多个订单以半角逗号相隔，如”123,456”，最多支持200个订单号  string
		}
		err := l.syncOrderStatusFromErp(queryMap)
		if err != nil {
			return nil, err
		}
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     "查询ERP订单发货状态成功",
		// Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}

func (l *SyncOrderStatusFromErpLogic) syncOrderStatusFromErp(queryMap map[string]string) error {
	// 文档地址：https://open.hupun.com/api-doc/erp/b2c/trades/erp/status
	path := "/erp/b2c/trades/erp/status"
	erpClient := erp.NewErp(l.svcCtx.Config.Erp.AppKey, l.svcCtx.Config.Erp.Secret, l.svcCtx.Config.Erp.Url, path)

	logx.Infof("syncOrderStatusFromErp queryMap : %+v ", queryMap)
	//
	err := erpClient.GetSign(queryMap)
	if err != nil {
		logx.Errorw("syncOrderStatusFromErp GetSign err", logx.Field("detail", err.Error()))
		return err
	}

	resMap, err := erpClient.CallErpApi()
	if err != nil {
		logx.Errorw("syncOrderStatusFromErp CallErpApi err", logx.Field("detail", err.Error()))
		return err
	}

	logx.Infof("syncOrderStatusFromErp response : %+v ", resMap)

	//map[response:{"statuses":[{"sale_tax_sn":"","express_code":"ZTO","express_local":"0002","waybill":"123456","tradeNo":"XD250613000031","shippingType":"0","packingInfos":[],"express":"中通快递","orders":[{"itemID":"11","orderstatus":"5","orderID":"O20250603203613144792001_54","skuID":"54"},{"itemID":"9","orderstatus":"5","orderID":"O20250603203613144792001_53","skuID":"53"},{"itemID":"10","orderstatus":"5","orderID":"O20250603203613144792001_82","skuID":"82"},{"itemID":"10","orderstatus":"5","orderID":"O20250603203613144792001_81","skuID":"81"}],"tid":"O20250603203613144792001","status":"8"}]} success:true]
	//response字段对应的数据结构，不返回信息，仅供参考数据格式
	res := resMap["response"].(string)
	logx.Infof("syncOrderStatusFromErp response1 : %+v ", res)
	//

	resp := map[string]any{}
	if err = json.Unmarshal([]byte(res), &resp); err != nil {
		logx.Errorw("syncOrderStatusFromErp json.Unmarshal err:", logx.Field("detail", err.Error()))
		// json: cannot unmarshal array into Go value of type map[string]interface {}
		return err
	}
	result := resp["statuses"].([]any)
	var data []*orderclient.UpdateTradeStateInfo
	if len(result) > 0 {
		for _, v := range result {
			sn := v.(map[string]any)["tid"].(string)
			status := v.(map[string]any)["status"].(string)
			orderRes := v.(map[string]any)["orders"].([]any)
			var orderItems []*orderclient.ErpOrderItem
			if len(orderRes) > 0 {
				for _, item := range orderRes {
					orderItem := item.(map[string]any)
					if skuId, ok := orderItem["skuID"].(string); ok {
						if itemId, err := strconv.ParseUint(skuId, 10, 64); err == nil || itemId > 0 {
							if orderStatus, ok := orderItem["orderstatus"].(string); ok {
								if itemStatus, err := strconv.ParseUint(orderStatus, 10, 64); err == nil {
									finalState := util.ErpOrderStatusToOrderStatus(uint32(itemStatus))
									orderItems = append(orderItems, &orderclient.ErpOrderItem{
										Id:         pointy.GetPointer(itemId),
										TradeState: pointy.GetPointer(finalState),
									})
								}
							}
						}
					}
				}
			}
			orderStatus, err := strconv.ParseUint(status, 10, 64)
			if err != nil {
				continue
			}
			finalState := util.ErpOrderStatusToOrderStatus(uint32(orderStatus))
			data = append(data, &orderclient.UpdateTradeStateInfo{
				Sn:                  pointy.GetPointer(sn),
				TradeState:          pointy.GetPointer(finalState),
				ExpressName:         nil,
				ExpressCode:         nil,
				Waybill:             nil,
				PaymentId:           nil,
				TransactionId:       nil,
				RefundId:            nil,
				RefundTransactionId: nil,
				OrderItem:           orderItems,
			})
			if len(data) > 0 {
				_, err = l.svcCtx.OrderRpc.UpdateTradeStateBatch(l.ctx, &orderclient.UpdateTradeStateBatchReq{
					Data: data,
				})
				if err != nil {
					logx.Errorf("UpdateTradeState sn:%s, err:%v", sn, err)
				}
			}
		}
	}

	// stockMap := map[string]uint64{}
	// for _, vv := range resp {
	// 	stockMap[v["sku_id"]] = uint64(vv["available"].(float64))
	// }

	// _, err = l.svcCtx.ProductRpc.UpdateProductStock(l.ctx, &productclient.UpdateProductStockReq{
	// 	Data: stockMap,
	// })
	// if err != nil {
	// 	logx.Errorw("syncOrderStatusFromErp UpdateProductStock Error:", logx.Field("detail", err.Error()))
	// 	return 0, err
	// }

	return nil
}
